<?php

namespace api\modules\app\models;

use Exception;
use Yii;
use yii\base\InvalidCallException;
use yii\base\UnknownPropertyException;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;

class BaseModel extends \yii\db\ActiveRecord
{
    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('test_3');
    }

    // public function attributes()
    // {
    //     return ['event_id', 'code', 'name'];
    // }

    public function getListColumns()
    {
        $table = static::tableName();
        $columns = $this->attributeLabels();
        foreach ($columns as $key => $value) {
            $data[] = "$table.$key as $table-$key";
        }
        return $data;
    }

    public static function getByEventId($evenId)
    {
        return static::findOne(['event_id' => $evenId]);
    }

    public function __get($name)
    {
        $name = Inflector::underscore($name);

        return parent::__get($name);
    }

    public function __set($name, $value)
    {
        $name = Inflector::underscore($name);

        return parent::__set($name, $value);
    }

    public function __call($name, $params)
    {
        if (StringHelper::startsWith($name, 'get')) {
            $field = substr($name, 3);
        }
        if (in_array(Inflector::underscore($field), array_keys($this->attributes))) {
            return $this[Inflector::underscore($field)];
        }
        return parent::__call($name, $params);
    }

    public function save($runValidation = true, $attributeNames = null)
    {
        if (!parent::save($runValidation, $attributeNames)) {
            throw new Exception(json_encode($this->getErrors()));
        }
        return true;
    }
}
